<template>
  <el-dialog
    v-model="dialogVisible"
    title="推送排产"
    width="800px"
    @close="handleClose"
  >
    <div class="production-preview">
      <!-- 加工单号信息 -->
      <div class="order-info">
        <span class="label">生产加工单号:</span>
        <span class="value">{{ orderNumber || 'SCJGDH001' }}</span>
        <span class="example">(示例)</span>
      </div>

      <!-- 表格数据 -->
      <div class="table-container">
        <el-table
          :data="currentPageData"
          border
          style="width: 100%"
        >
          <!-- 动态表头，支持合并表头 -->
          <template v-for="(header, index) in tableHeaders" :key="index">
          <!-- 普通表头 -->
          <template v-if="!header.children || header.children.length === 0">
            <el-table-column
              align="center"
              :prop="header.prop"
              :label="header.label"
            >
              <template #default="{ row }">
                {{ getCellValue(row, header.prop) }}
              </template>
            </el-table-column>
          </template>
          <!-- 有子列的表头（需要合并） -->
          <template v-else>
            <el-table-column
              :label="header.label"
              align="center"
            >
              <template v-for="(child, childIndex) in header.children" :key="childIndex">
                <el-table-column
                  :prop="child.prop"
                  :label="child.label"
                  align="center"
                >
                  <template #default="{ row }">
                    {{ getCellValue(row, child.prop) }}
                  </template>
                </el-table-column>
              </template>
            </el-table-column>
          </template>
        </template>
        </el-table>
      </div>

      <!-- 分组和统计信息 -->
      <div class="group-stats">
        <div class="stats-row">
          <div class="stats-column" v-for="(group, index) in groupInfo" :key="index">
            <span class="label">{{ group.label }}:</span>
            <span class="value">{{ group.name }}</span>
          </div>
        </div>
        <div class="stats-row">
          <div class="stats-column" v-for="(stat, index) in statistics" :key="index">
            <span class="label">{{ stat.label }}:</span>
            <span class="value">{{ stat.value }}</span>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="prev, pager, next"
          :total="totalData"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'ProductionSchedulingPush',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:visible', 'close', 'confirm'],
  setup(props, { emit }) {
    const dialogVisible = computed({
      get: () => props.visible,
      set: (value) => emit('update:visible', value)
    })

    // 表格配置
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalData = ref(0)
    const orderNumber = ref('')
    const splitCount = ref(0)

    // 模拟数据 - 表头配置
    const tableHeaders = ref([
      {
        label: '颜色',
        prop: 'color',
        type: 'attribute'
      },
      {
        label: '工艺',
        prop: 'process',
        type: 'attribute'
      },
      {
        label: '产品信息',
        children: [
          {
            label: '品名',
            prop: 'productName',
            type: 'product'
          },
          {
            label: '面积',
            prop: 'area',
            type: 'product'
          },
          {
            label: '长度',
            prop: 'length',
            type: 'product'
          }
        ]
      }
    ])

    // 模拟数据 - 表格数据
    const tableData = ref([])

    // 模拟数据 - 分组信息
    const groupInfo = ref([
      { type: 'color', label: '颜色', name: '按颜色分组' },
      { type: 'process', label: '工艺', name: '按工艺分组' },
      { type: 'product', label: '品名', name: '按品名分组' }
    ])

    // 模拟数据 - 统计信息
    const statistics = ref([
      { type: 'area', label: '面积', value: '统计面积总和' },
      { type: 'glue', label: '胶水用量', value: '统计胶水用量总和' },
      { type: 'plastic', label: '塑粉用量', value: '统计塑粉用量总和' }
    ])

    // 当前页数据
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return tableData.value.slice(start, end)
    })

    // 获取单元格值
    const getCellValue = (row, prop) => {
      return row[prop] || ''
    }

    // 处理页码变化
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    // 处理每页条数变化
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }

    // 处理关闭
    const handleClose = () => {
      emit('close')
    }

    // 处理确认
    const handleConfirm = () => {
      emit('confirm')
      ElMessage.success('推送排产成功')
      dialogVisible.value = false
    }

    // 生成模拟数据
    const generateMockData = () => {
      const mockData = []
      const colors = ['红', '蓝', '黑', '白']
      const processes = ['工艺1', '工艺2', '工艺3']
      const products = ['品1', '品2', '品3', '品4', '品5']
      
      // 生成200条模拟数据
      for (let i = 0; i < 200; i++) {
        mockData.push({
          color: colors[Math.floor(Math.random() * colors.length)],
          process: processes[Math.floor(Math.random() * processes.length)],
          productName: products[Math.floor(Math.random() * products.length)],
          area: String.fromCharCode(65 + Math.floor(Math.random() * 26)), // A-Z
          length: String.fromCharCode(97 + Math.floor(Math.random() * 26)) // a-z
        })
      }
      
      // 按颜色、工艺、产品分组排序
      mockData.sort((a, b) => {
        if (a.color !== b.color) return a.color.localeCompare(b.color)
        if (a.process !== b.process) return a.process.localeCompare(b.process)
        return a.productName.localeCompare(b.productName)
      })
      
      return mockData
    }

    // 监听数据变化
    watch(() => props.visible, (newVal) => {
      if (newVal) {
        // 初始化数据
        tableData.value = generateMockData()
        totalData.value = tableData.value.length
        orderNumber.value = 'SCJGDH001'
        splitCount.value = Math.ceil(totalData.value / 10)
        currentPage.value = 1
      }
    })

    // 监听props.data变化，可以根据实际传入的数据调整
    watch(() => props.data, (newData) => {
      if (newData && Object.keys(newData).length > 0) {
        // 这里可以根据实际传入的数据进行处理
        orderNumber.value = newData.orderNumber || 'SCJGDH001'
      }
    }, { deep: true })

    return {
      dialogVisible,
      tableHeaders,
      currentPageData,
      currentPage,
      pageSize,
      totalData,
      groupInfo,
      statistics,
      orderNumber,
      splitCount,
      getCellValue,
      handleCurrentChange,
      handleSizeChange,
      handleClose,
      handleConfirm
    }
  }
}
</script>

<style scoped>
.production-preview {
  padding: 10px 10px;
  border: 1px solid #e0e0e0;
}

.order-info {
  margin-bottom: 16px;
  font-size: 14px;
}

.order-info .label {
  font-weight: bold;
  margin-right: 8px;
}

.order-info .value {
  color: #1890ff;
  margin-right: 8px;
}

.order-info .example {
  color: #909399;
  font-size: 12px;
}

.table-container {
  margin-bottom: 16px;
  overflow-x: auto;
}

.group-stats {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stats-row {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.stats-column {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  text-align: left;
  padding-right: 10px;
}

.stats-column .label {
  font-weight: normal;
  margin-right: 4px;
  white-space: nowrap;
}

.stats-column .value {
  white-space: nowrap;
  color: #1890ff;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.confirm-info {
  background-color: #f0f9ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 16px;
}

.confirm-message {
  display: flex;
  align-items: center;
  font-size: 14px;
  margin-bottom: 8px;
}

.confirm-message i {
  margin-right: 8px;
  font-size: 16px;
}

.sub-message {
  font-size: 13px;
  color: #606266;
  margin-left: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: center;
}

.dialog-footer button {
  margin: 0 8px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .group-info,
  .stats-info {
    flex-direction: column;
  }
  
  .group-item,
  .stat-item {
    margin-bottom: 8px;
  }
}
</style>